<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="订单编号" prop="orderSn">
        <el-input v-model="queryParams.orderSn" placeholder="请输入订单编号,模糊匹配" clearable style="width: 200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--
      <el-form-item label="订单ID" prop="id">
        <el-input v-model="queryParams.id" placeholder="请输入订单ID" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      -->
      <el-form-item label="客户名称" prop="purchaserName">
        <el-input v-model="queryParams.purchaserName" placeholder="请输入客户名称,模糊匹配" clearable
          style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="登录账号" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入登录账号/收货电话,模糊匹配" clearable
          style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户编号" prop="businessCode">
        <el-input v-model="queryParams.businessCode" placeholder="请输入客户编号,精准匹配" clearable
          style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品编号" prop="identifier">
        <el-input v-model="queryParams.identifier" placeholder="商品编号,多个编号之间用逗号分割" clearable
          style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="付款流水号" prop="receivableNo">
        <el-input v-model="queryParams.receivableNo" placeholder="付款流水号,模糊匹配" clearable
          style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="出库单号" prop="outboundOrderSn">
        <el-input v-model="queryParams.outboundOrderSn" placeholder="出库单号,模糊匹配" clearable
          style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="queryParams.paymentMethod" placeholder="支付方式,精准匹配" clearable multiple
          style="width: 200px">
          <el-option v-for="dict in dict.type.pay_way" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="订单状态,精准匹配" clearable multiple
          style="width: 200px">
          <el-option v-for="dict in dict.type.order_order_status" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="付款状态" prop="payStatus">
        <el-select v-model="queryParams.payStatus" placeholder="付款状态,精准匹配" clearable multiple
          style="width: 200px">
          <el-option v-for="dict in dict.type.order_pay_status" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="货运状态" prop="deliverStatus">
        <el-select v-model="queryParams.deliverStatus" placeholder="货运状态,精准匹配" clearable
          style="width: 200px">
          <el-option v-for="dict in dict.type.order_deliver_status" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="内部状态" prop="innerStatus">
        <el-select v-model="queryParams.innerStatus" placeholder="内部执行状态,精准匹配" clearable multiple
          style="width: 200px">
          <el-option v-for="dict in dict.type.order_inner_status" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间">
        <el-date-picker v-model="payDateRange" style="width: 220px" value-format="yyyy-MM-dd"
          clearable type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期" clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker v-model="dateRange" style="width: 220px" value-format="yyyy-MM-dd" clearable
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="推广手机号" prop="promotePhoneNumber">
        <el-input v-model="queryParams.promotePhoneNumber" placeholder="推广人员手机号,模糊匹配" clearable
          style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini"
          @click="handleEditTable(undefined)" v-hasPermi="['system:role:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleEditTable" v-hasPermi="['system:role:edit']">修改</el-button>
      </el-col>
      -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini"
          @click="handleSummaryExport" v-hasPermi="['order:order:summary:export']">导出订单汇总
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini"
          @click="handleDetailExport" v-hasPermi="['order:order:detail:export']">导出订单明细</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download" size="mini" :disabled="single"
          @click="maintenancePromotionInfo"
          v-hasPermi="['order:order:promotePhoneNumber:edit']">维护推荐人</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- :disabled="!synchronizeOrders" -->
        <el-button type="success" plain icon="el-icon-grape" size="mini"
          @click="handleSynchronizeOrders" v-hasPermi="['order:order:sync']">同步到ERP</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- :disabled="!synchronizeOrders" -->
        <el-button type="danger" plain icon="el-icon-grape" size="mini" :disabled="single"
          @click="handleDeleteERPOrder" v-hasPermi="['order:order:erp:delete']">删除ERP订单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns">
      </right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="42" align="center" />
      <el-table-column :label="columns[0].label" :prop="columns[0].prop" :width="columns[0].width"
        :show-overflow-tooltip="true" v-if="columns[0].visible">
        <template slot-scope="scope">
          <router-link :to="'/order/order-detail/' + scope.row.id" class="link-type">
            <span>{{ scope.row.sn }}</span>
          </router-link>
          <el-button size="mini" type="text" icon="el-icon-document-copy" id="sn" :value="scope.row.sn" style="margin-left: 3px;"></el-button>
        </template>
      </el-table-column>
      <el-table-column :label="columns[1].label" :prop="columns[1].prop" :width="columns[1].width"
        :show-overflow-tooltip="true" v-if="columns[1].visible">
        <template slot-scope="scope">
          <router-link :to="'/order/order-detail/' + scope.row.id" class="link-type">
            <span>{{ scope.row.id }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column :label="columns[2].label" :prop="columns[2].prop"
        :show-overflow-tooltip="true" :min-width="columns[2].minWidth" v-if="columns[2].visible" />
      <el-table-column :label="columns[3].label" :prop="columns[3].prop"
        :show-overflow-tooltip="true" :width="columns[3].width" v-if="columns[3].visible" />
      <el-table-column :label="columns[4].label" :prop="columns[4].prop"
        :show-overflow-tooltip="true" :width="columns[4].width" v-if="columns[4].visible" />
      <el-table-column :label="columns[5].label" :prop="columns[5].prop"
        :show-overflow-tooltip="true" :width="columns[5].width" v-if="columns[5].visible" />
      <el-table-column :label="columns[6].label" :prop="columns[6].prop"
        :show-overflow-tooltip="true" :width="columns[6].width" v-if="columns[6].visible" />
      <el-table-column :label="columns[7].label" :prop="columns[7].prop"
        :show-overflow-tooltip="true" :width="columns[7].width" v-if="columns[7].visible" />
      <el-table-column :label="columns[8].label" :prop="columns[8].prop"
        :show-overflow-tooltip="true" :width="columns[8].width" v-if="columns[8].visible" />
      <el-table-column :label="columns[9].label" :prop="columns[9].prop"
        :show-overflow-tooltip="true" :width="columns[9].width" v-if="columns[9].visible" />
      <el-table-column :label="columns[10].label" :prop="columns[10].prop"
        :show-overflow-tooltip="true" :width="columns[10].width" v-if="columns[10].visible" />
      <el-table-column :label="columns[11].label" :prop="columns[11].prop" align="center"
        :show-overflow-tooltip="true" :width="columns[11].width" v-if="columns[11].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_order_status" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="columns[12].label" :prop="columns[12].prop" align="center"
        :show-overflow-tooltip="true" :width="columns[12].width" v-if="columns[12].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_inner_status" :value="scope.row.innerStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="columns[13].label" :prop="columns[13].prop" align="center"
        :width="columns[13].width" v-if="columns[13].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_pay_status" :value="scope.row.payStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="columns[14].label" :prop="columns[14].prop"
        :show-overflow-tooltip="true" :width="columns[14].width" v-if="columns[14].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_way" :value="scope.row.paymentMethod" />
        </template>
      </el-table-column>
      <el-table-column :label="columns[15].label" :prop="columns[15].prop"
        :show-overflow-tooltip="true" :width="columns[15].width" v-if="columns[15].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_way" :value="scope.row.paymentChannel" />
        </template>
      </el-table-column>
      <el-table-column :label="columns[16].label" :prop="columns[16].prop"
        :show-overflow-tooltip="true" :width="columns[16].width" v-if="columns[16].visible" />
      <el-table-column :label="columns[17].label" :prop="columns[17].prop" align="center"
        :width="columns[17].width" v-if="columns[17].visible">
        <template slot-scope="scope">
          {{scope.row.afterSaleStatus?'有售后单':''}}
        </template>
      </el-table-column>
      <el-table-column :label="columns[18].label" :prop="columns[18].prop" align="center"
        :width="columns[18].width" v-if="columns[18].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_deliver_status" :value="scope.row.deliverStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="columns[19].label" :prop="columns[19].prop"
        :show-overflow-tooltip="true" :width="columns[19].width" v-if="columns[19].visible" />
      <el-table-column :label="columns[20].label" :prop="columns[20].prop"
        :show-overflow-tooltip="true" :width="columns[20].width" v-if="columns[20].visible" />
      <el-table-column :label="columns[21].label" :prop="columns[21].prop"
        :show-overflow-tooltip="true" :width="columns[21].width" v-if="columns[21].visible" />
      <el-table-column :label="columns[22].label" :prop="columns[22].prop"
        :show-overflow-tooltip="true" :width="columns[22].width" v-if="columns[22].visible" />
      <el-table-column :label="columns[23].label" :prop="columns[23].prop" align="center"
        :show-overflow-tooltip="true" :width="columns[23].width" v-if="columns[23].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_client_type" :value="scope.row.clientType" />
        </template>
      </el-table-column>
      <el-table-column :label="columns[24].label" :prop="columns[24].prop"
        :show-overflow-tooltip="true" :width="columns[24].width" v-if="columns[24].visible" />
      <el-table-column :label="columns[25].label" :prop="columns[25].prop"
        :show-overflow-tooltip="true" :width="columns[25].width" v-if="columns[25].visible" />
      <el-table-column :label="columns[26].label" align="center" :prop="columns[26].prop"
        :show-overflow-tooltip="true" :width="columns[26].width" v-if="columns[26].visible">
      </el-table-column>
      <el-table-column :label="columns[27].label" align="center" :prop="columns[27].prop"
        :show-overflow-tooltip="true" :width="columns[27].width" v-if="columns[27].visible">
      </el-table-column>
      <el-table-column :label="columns[28].label" align="center" :prop="columns[28].prop"
        :width="columns[28].width" v-if="columns[28].visible" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column :label="columns[29].label" align="center" :prop="columns[29].prop"
        :width="columns[29].width" v-if="columns[29].visible" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column :label="columns[30].label" align="center" :prop="columns[30].prop"
        :width="columns[30].width" v-if="columns[30].visible" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column :label="columns[31].label" align="center" :prop="columns[31].prop"
        :width="columns[31].width" v-if="columns[31].visible" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column :label="columns[32].label" align="center" :prop="columns[32].prop"
        :width="columns[32].width" v-if="columns[32].visible" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column :label="columns[33].label" align="center" :prop="columns[33].prop"
        :width="columns[33].width" v-if="columns[33].visible" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column :label="columns[34].label" align="center" :prop="columns[34].prop"
        :width="columns[34].width" v-if="columns[34].visible" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column :label="columns[35].label" align="center" :prop="columns[35].prop"
        :width="columns[35].width" v-if="columns[35].visible" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditTable(scope.row)"
            v-hasPermi="['order:order:query']">详情</el-button>

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['order:order:createTime:edit', 'order:order:invalid:edit', 'order:order:traces:query', 'order:order:receipt:edit']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-show="scope.row.orderStatus=='CANCELLED' && scope.row.payStatus=='UNPAID'"
                command="restoreOrder" icon="el-icon-circle-check"
                v-hasPermi="['order:order:createTime:edit']">恢复订单</el-dropdown-item>
              <el-dropdown-item v-show="scope.row.orderStatus=='UNPAID'" command="openHandleSelectDate" icon="el-icon-grape"
                v-hasPermi="['order:order:createTime:edit']">保留订单</el-dropdown-item>
              <el-dropdown-item v-show="scope.row.orderStatus=='CANCELLED' && scope.row.payStatus=='UNPAID'" command="handleHideOrder" icon="el-icon-delete"
                v-hasPermi="['order:order:invalid:edit']">删除订单</el-dropdown-item>
              <el-dropdown-item v-show="scope.row.logisticsNo" command="showLogisticsTraces" icon="el-icon-truck"
                v-hasPermi="['order:order:traces:query']">物流轨迹</el-dropdown-item>
              <el-dropdown-item v-show="scope.row.orderStatus == 'COMPLETED' && scope.row.receipt == 'NOT_YET_DUE'" command="invoicable" icon="el-icon-truck"
                v-hasPermi="['order:order:receipt:edit']">可开发票</el-dropdown-item>
              <el-dropdown-item v-show="scope.row.innerStatus === 'AWAIT' || scope.row.innerStatus === 'UNDETERMINED' || scope.row.innerStatus === 'EXPCT_PURCHASER' || scope.row.innerStatus === 'NOT_PUSHED' || scope.row.innerStatus === 'PUSHED' || scope.row.innerStatus === 'ACCEPTANCE'"
                command="handleOpenChangeOrderBusinessCodeView" icon="el-icon-edit" v-hasPermi="['order:order:purchaser:change']">更换客户</el-dropdown-item>
              <el-dropdown-item v-show="(scope.row.innerStatus === 'UNDETERMINED' || scope.row.innerStatus === 'EXPCT_PURCHASER') && scope.row.businessCode"
                command="handleNotpush" icon="el-icon-grape" v-hasPermi="['order:order:innerStatus:notPushed:edit']">待推送</el-dropdown-item>
              <el-dropdown-item v-show="scope.row.innerStatus === 'UNDETERMINED' || scope.row.innerStatus === 'PUSHED' || scope.row.innerStatus === 'ACCEPTANCE' || scope.row.innerStatus === 'PACKAGED'"
                command="handleRepush" icon="el-icon-grape" v-hasPermi="['order:order:innerStatus:edit']">重新推送</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 打开商品SKU促销状态对话框 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag title="确认商品促销价格" :visible.sync="openPromotionFlag" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="促销价格" prop="promotionPrice">
              <el-input-number v-model="form.promotionPrice" controls-position="left" :min="0.01" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"
          @click="handlePromotionStatusChange(currentRow, form.promotionPrice)">确 定</el-button>
        <el-button @click="closePromotionFlagView">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag title="物流信息" :visible.sync="logisticsVisible" width="888px" append-to-body>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane v-for="(items,index) in tracesList" :key="index" :label="'包裹'+(index+1)"
          :name="index.toString()">
          <p class="title">{{items.shipper}} 货运单号：{{items.logisticCode}}</p>
          <div class="content">
            <div v-for="(item,ii) in items.traces" :key="ii" class="items">
              <p>{{item.opeTime}}</p>
              <p> <i></i> <i></i> </p>
              <p>{{item.opeRemark}}</p>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="warning" v-hasPermi="['order:order:status:edit']"
          @click="completed">已收货</el-button>
        <el-button type="primary" @click="logisticsVisible = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag title="订单保留时间" :visible.sync="selectionDate" width="400px">
      <div style="height:50px;padding-top:10px;text-align:center;">
        <el-date-picker v-model="selectDateValue" type="datetime" placeholder="请选择日期时间">
        </el-date-picker>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" @click="selectionDate=false">取消</el-button>
        <el-button type="primary" @click="selectionDateDetermine()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag title="订单保留时间" :visible.sync="restoreOrderView" width="400px">
      <div style="height:50px;padding-top:10px;text-align:center;">
        <el-date-picker v-model="selectDateValue" type="datetime" placeholder="请选择日期时间">
        </el-date-picker>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" @click="restoreOrderView=false">取消</el-button>
        <el-button type="primary" @click="restoreOrder()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag title="订单更换客户" :visible.sync="changeOrderBusinessCodeView" width="400px">
      <div style="height:50px;padding-top:10px;text-align:center;">
        <el-input v-model="changeOrderBusinessCode" placeholder="请输入客户编号" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" @click="changeOrderBusinessCodeView=false">取消</el-button>
        <el-button type="primary" @click="updateOrderBusinessCode()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSimpleOrder, getLogisticsTraces, updatePromotePhoneNumber, updOrderStatus, hideOrder, keepOrder,
  changePurchaser, updateInnerStatus, invoicable } from "@/api/order/order"
import axios from 'axios'
import ClipboardJS from 'clipboard'

export default {
  name: "Order",
  dicts: [
    "order_client_type",
    "order_order_status",
    "order_pay_status",
    "order_deliver_status",
    "order_inner_status",
    "pay_way",
    "after_sale_status"
  ],
  data () {
    return {
      // 遮罩层
      loading: true,
      openPromotionFlag: false,
      // 选中数组
      ids: [],
      // 选中数组
      sns: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      // 支付日期范围
      payDateRange: [],
      // 日期范围
      dateRange: [],
      // 列信息
      columns: [
        { key: 0, label: `订单编号`, prop: "sn", width: 195, visible: true },
        { key: 1, label: `订单ID`, prop: "id", width: 175, visible: false },
        { key: 2, label: `客户名称`, prop: "purchaserName", width: 210, minWidth: 200, visible: true },
        { key: 3, label: `联系电话`, prop: "consigneeMobile", width: 120, visible: true },
        { key: 4, label: `订单原价`, prop: "goodsPrice", width: 80, visible: false },
        { key: 5, label: `运费`, prop: "freightPrice", width: 50, visible: false },
        { key: 6, label: `优惠金额`, prop: "discountPrice", width: 80, visible: false },
        { key: 7, label: `应付金额`, prop: "flowPrice", width: 75, visible: true },
        { key: 8, label: `出库金额`, prop: "outboundFlowPrice", width: 75, visible: false },
        { key: 9, label: `退款金额`, prop: "refundFlowPrice", width: 75, visible: false },
        { key: 10, label: `商品数量`, prop: "goodsNum", width: 75, visible: false },
        { key: 11, label: `订单状态`, prop: "orderStatus", width: 75, visible: true },
        { key: 12, label: `内部状态`, prop: "innerStatus", width: 75, visible: true },
        { key: 13, label: `付款状态`, prop: "payStatus", width: 80, visible: true },
        { key: 14, label: `支付方式`, prop: "paymentMethod", width: 80, visible: false },
        { key: 15, label: `支付通道`, prop: "paymentChannel", width: 80, visible: false },
        { key: 16, label: `支付时间`, prop: "paymentTime", width: 150, visible: true },
        { key: 17, label: `售后单`, prop: "afterSaleStatus", width: 80, visible: true },
        { key: 18, label: `货运状态`, prop: "deliverStatus", width: 75, visible: false },
        { key: 19, label: `物流单号`, prop: "logisticsNo", width: 145, visible: false },
        { key: 20, label: `物流公司名称`, prop: "logisticsName", width: 100, visible: false },
        { key: 21, label: `买家备注`, prop: "remark", width: 180, visible: true },
        { key: 22, label: `订单取消原因`, prop: "cancelReason", width: 150, visible: false },
        { key: 23, label: `订单来源`, prop: "clientType", width: 80, visible: false },
        { key: 24, label: `付款流水号`, prop: "receivableNo", width: 240, visible: false },
        { key: 25, label: `推销员手机号`, prop: "promotePhoneNumber", width: 120, visible: false },
        { key: 26, label: `推销员姓名`, prop: "promoteMan", width: 120, visible: false },
        { key: 27, label: `下单时间`, prop: "createTime", width: 150, visible: false },
        { key: 28, label: `完成时间`, prop: "completeTime", width: 150, visible: false },
        { key: 29, label: `客户编号`, prop: "businessCode", width: 80, visible: true },
        { key: 30, label: `省`, prop: "consigneeProvince", width: 80, visible: true },
        { key: 31, label: `市`, prop: "consigneeCity", width: 80, visible: true },
        { key: 32, label: `区/县`, prop: "consigneeCounty", width: 80, visible: false },
        { key: 33, label: `详细地址`, prop: "consigneeDetail", width: 300, visible: false },
        { key: 34, label: `收货人`, prop: "consigneeName", width: 200, visible: false },
        { key: 35, label: `出库单号`, prop: "outboundOrderSn", width: 150, visible: false },
      ],
      // 当前行数据
      currentRow: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderSn: '',
        id: '',
        purchaserName: '',
        businessCode: '',
        username: '',
        memberName: '',
        outboundOrderSn: '',
        paymentMethod: '',
        orderStatus: '',
        payStatus: '',
        deliverStatus: '',
        innerStatus: '',
        refundFlowPriceFlag: false,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        promotionPrice: [
          { required: true, message: "促销价格不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      },
      synchronizeOrders: false,
      shipper: '',
      logisticCode: '',
      tracesList: '',
      logisticsVisible: false,
      activeName: '0',
      order: undefined,
      selectionDate: false,
      selectDateValue: '',
      restoreOrderView: false,

      changeOrderBusinessCodeView: false,
      changeOrderBusinessCodeSn: '',
      changeOrderBusinessCode: '',
    }
  },
  mounted() {
    const snClipboard = new ClipboardJS('#sn', {
      text: trigger => {
        this.$notify({
          title: '成功',
          message: '订单编号已复制到剪切板，可粘贴。',
          type: 'success'
        })
        return trigger.value
      }
    })
    snClipboard.on('error', e => {
      this.$message.error('订单编号复制失败')
    })
  },
  created () { this.resetQuery() },
  methods: {
    // 打开 调整时间 弹窗
    openHandleSelectDate (row) {
      this.selectDateValue = row.createTime
      this.order = row
      this.selectionDate = true
    },
    // 调整时间 弹窗 确认按钮
    selectionDateDetermine () {
      keepOrder(this.order.sn, {createTime: this.parseTime(this.selectDateValue)})
      .then(res=>{
          this.$modal.msgSuccess("订单保留至【" + this.parseTime(this.selectDateValue) + "】")
          this.selectionDate = false
      });
    },

    //
    handleClick () { },
    handleSynchronizeOrders () {
      //window.open('http://www.xdyy365.com:5003/wholesale/sync-api/order/check', '_black')
      window.open('http://www.xdyy365.com:5003/wholesale/sync-api/order/refresh', '_black')
      // axios({ method: 'get', url: 'http://www.xdyy365.com:5003/wholesale/sync-api/order/refresh', }).then(res => {
      //   console.log(res)
      // })
    },
    handleDeleteERPOrder (row) {
      let orderSn = row.sn || this.sns;
      this.$modal.confirm('确认删除ERP中的订单吗？').then(function () {
        window.open('http://www.xdyy365.com:5003/wholesale/sync-api/order/delete/' + orderSn, '_black');
        //window.open('http://10.10.2.5:5003/wholesale/sync-api/order/delete/' + orderSn, '_black');
      }).catch(function () { });
    },
    /** 查询订单列表 */
    getList () {
      if(!this.$auth.hasRole("admin") && this.$auth.hasRole("offlinesaler")){
        this.queryParams.userId = this.$store.state.user.userId;
      }

      this.loading = true;
      if(this.queryParams.orderSn){
        this.queryParams.orderSn = this.queryParams.orderSn.toUpperCase().trim();
      }
      if(this.queryParams.purchaserName){
        this.queryParams.purchaserName = this.queryParams.purchaserName.trim();
      }
      if(this.queryParams.businessCode){
        this.queryParams.businessCode = this.queryParams.businessCode.toUpperCase().trim();
      }
      if(this.queryParams.receivableNo){
        this.queryParams.receivableNo = this.queryParams.receivableNo.toUpperCase().trim();
      }
      if(this.queryParams.username){
        this.queryParams.username = this.queryParams.username.trim();
      }
      if(this.queryParams.outboundOrderSn){
        this.queryParams.outboundOrderSn = this.queryParams.outboundOrderSn.toUpperCase().trim();
      }
      if(this.queryParams.promotePhoneNumber){
        this.queryParams.promotePhoneNumber = this.queryParams.promotePhoneNumber.trim()
      }
      this.queryParams.refundFlowPriceFlag = this.columns[9].visible;
      this.queryParams.paramMap = {
        outboundOrderSnFlag: this.columns[35].visible,
      }
      this.queryParams.promoteManFlag = this.columns[26].visible

      listSimpleOrder(
        this.addDateRangeWithMap(this.addDateRangeWithMap(this.queryParams, this.dateRange, "CreateTime"), this.payDateRange, "PaymentTime")
      ).then(response => {
        this.orderList = response.rows;

        this.total = response.total;
        this.loading = false;
      }).catch((err)=>{
        console.log(err)
      });
    },
    //商品促销状态窗口 关闭
    closePromotionFlagView () {
      this.openPromotionFlag = false;
      this.currentRow.promotionFlag = !this.currentRow.promotionFlag;
    },
    // 促销状态修改
    handlePromotionStatusChange (row, promotionPrice) {
      let text = row.promotionFlag === true ? "促销" : "取消促销";
      this.$modal.confirm('确认"' + text + '""' + row.goodsName + '"商品吗？')
        .then(function () {
          return changeGoodsSkuPromotionFlag(
            row.goodsId,
            row.id,
            row.promotionFlag,
            promotionPrice
          );
        }).then(() => {
          this.openPromotionFlag = false;
          row.promotionPrice = promotionPrice;

          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.promotionFlag = !row.promotionFlag;
        });
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      let pattern = "{y}-{m}-{d}"
      this.dateRange = [this.addOrReduceDate(new Date(), pattern, 0, 0, -10), this.parseTime(new Date().getTime(), pattern)];

      this.payDateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id);
      this.sns = selection.map(item => item.sn);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增/修改按钮操作 */
    handleEditTable (row) {
      //const params = {}
      //if (row) { params.id = row.id }
      //const tabTitle = row ? "订单详情" : "新增订单";
      //this.$tab.openPage(tabTitle, "/order/order-sku-edit/orderListDetails", params);

      this.$router.push("/order/order-detail/" + row.id);
    },
    // 展示物流轨迹信息
    showLogisticsTraces (row) {
      this.order = row
      getLogisticsTraces(row.id).then(res => {
        if (res.code === 200) {
          this.tracesList = res.data
          // this.shipper = res.data.shipper
          // this.logisticCode = res.data.logisticCode
          this.logisticsVisible = true
        }
      })
    },
    /** 导出订单汇总按钮操作 */
    handleSummaryExport () {
      if(!this.$auth.hasRole("admin") && this.$auth.hasRole("offlinesaler")){
        this.queryParams.userId = this.$store.state.user.userId;
      }
      this.queryParams.orderSn = this.queryParams.orderSn.toUpperCase();
      this.queryParams.businessCode = this.queryParams.businessCode.toUpperCase();
      this.queryParams.refundFlowPriceFlag = this.columns[9].visible;
      this.queryParams.paramMap = { promoteManFlag: this.columns[26].visible }

      const _this = this
      this.$modal.confirm('确认创建导出报表任务吗？')
        .then(function () {
          _this.download('order/order/summary/export', {
            ..._this.addDateRangeWithMap(_this.addDateRangeWithMap(_this.queryParams, _this.dateRange, "CreateTime"), _this.payDateRange, "PaymentTime")
          }, `订单汇总_${_this.parseTime(new Date().getTime(), "{y}-{m}-{d}_{h}{i}{s}")}.xlsx`)
        })
    },
    /** 导出订单明细按钮操作 */
    handleDetailExport () {
      if(!this.$auth.hasRole("admin") && this.$auth.hasRole("offlinesaler")){
        this.queryParams.userId = this.$store.state.user.userId;
      }
      this.queryParams.orderSn = this.queryParams.orderSn.toUpperCase();
      this.queryParams.businessCode = this.queryParams.businessCode.toUpperCase();
      this.queryParams.refundFlowPriceFlag = this.columns[9].visible;
      this.queryParams.paramMap = { promoteManFlag: this.columns[26].visible }

      const _this = this
      this.$modal.confirm('确认创建导出报表任务吗？')
        .then(function () {
        _this.download('order/order/detail/export', {
          ..._this.addDateRangeWithMap(_this.addDateRangeWithMap(_this.queryParams, _this.dateRange, "CreateTime"), _this.payDateRange, "PaymentTime")
        }, `订单明细_${_this.parseTime(new Date().getTime(), "{y}-{m}-{d}_{h}{i}{s}")}.xlsx`)
      })
    },
    maintenancePromotionInfo (row) {
      let orderSn = row.sn || this.sns;
      let phoneNumber = ''
      this.orderList.forEach(order => {
        if (orderSn == order.sn) {
          phoneNumber = order.promotePhoneNumber
        }
      })

      this.$prompt('请输入推广人员手机号', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[1][0-9]{10}$/,
        inputErrorMessage: '手机号码格式不正确',
        inputValue: phoneNumber
      }).then(({ value }) => {
        updatePromotePhoneNumber(orderSn, { promotePhoneNumber: value }).then(res => {
          this.getList()
          this.$message({
            type: 'success',
            message: '将订单 ' + orderSn + '的推广手机号修改为' + value
          });
        })
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '取消输入'
        // });
      });
    },
    // 确认收货
    completed () {
      const currentOrder = { id: this.order.id, orderStatus: 'DELIVERED' }
      const _this = this
      this.$modal.confirm('确认订单' + this.order.sn + '"用户已收货了吗？').then(function () {
        updOrderStatus(currentOrder.id, currentOrder).then(res => {
          _this.$modal.msgSuccess("订单收货成功")
          _this.logisticsVisible = false
        })
      })
    },
    handleHideOrder (row) {
      let orderSn = row.sn

      const _this = this
      this.$modal.confirm('确认将订单' + orderSn + '"删除吗？').then(function () {
        hideOrder(orderSn).then(res => {
          _this.$modal.msgSuccess("订单删除成功")
          _this.getList()
        })
      })
    },
    openRestoreOrder (row){
      this.selectDateValue = this.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}")
      this.order = row
      this.restoreOrderView = true;
    },
    restoreOrder(){
      keepOrder(this.order.sn, {createTime: this.parseTime(this.selectDateValue)})
      .then(res=>{
          this.order.orderStatus = 'UNPAID';
          this.order.paymentMethod = '';
          this.order.paymentTime = '';

          this.$modal.msgSuccess("订单保留至【" + this.parseTime(this.selectDateValue) + "】")
          this.restoreOrderView = false;
      });
    },
    // 更多操作触发
    handleCommand (command, row) {
      switch (command) {
        case "restoreOrder":
          this.openRestoreOrder(row);
          break;
        case "openHandleSelectDate":
          this.openHandleSelectDate(row);
          break;
        case "handleHideOrder":
          this.handleHideOrder(row);
          break;
        case "showLogisticsTraces":
          this.showLogisticsTraces(row);
          break;
        case "invoicable":
          this.invoicableHandler(row);
          break;
        case "handleOpenChangeOrderBusinessCodeView":
          this.openChangeOrderBusinessCodeView(row)
          break;
        case "handleNotpush":
          this.repush(row, 'NOT_PUSHED')
          break;
        case "handleRepush":
          this.repush(row, 'RE_PUSH')
          break;
        default:
          break;
      }
    },
    openChangeOrderBusinessCodeView(row){
      // if(row){
      //   this.changeOrderBusinessCodeSn = row.sn;
      // } else {
      //   this.changeOrderBusinessCodeSn = row.sn || this.sns;
      // }
      this.changeOrderBusinessCodeSn = row.sn || this.sns;

      this.changeOrderBusinessCode = '';
      this.changeOrderBusinessCodeView = true;
    },
    updateOrderBusinessCode(){
      const _this = this
      this.$modal.confirm('确认将订单' + this.changeOrderBusinessCodeSn + '"的客户更换为' + this.changeOrderBusinessCode.replaceAll(" ", "").toUpperCase() + '的客户吗？').then(function () {
        changePurchaser(_this.changeOrderBusinessCodeSn, {businessCode: _this.changeOrderBusinessCode}).then(res => {
          _this.$modal.msgSuccess("订单更换客户成功")
          _this.getList()
          _this.changeOrderBusinessCodeView = false;
        })
      })
    },
    repush(row, innerStatus){
      const sn = row.sn || this.sns;

      const _this = this
      this.$modal.confirm('确认将订单' + sn + '重新推送到ERP吗？').then(function () {
        updateInnerStatus(sn, {innerStatus: innerStatus}).then(res => {
          _this.$modal.msgSuccess("订单重新推送成功")
          _this.getList()
        })
      })
    },
    //订单修改为可开发票
    invoicableHandler(row){
      const _this = this
      this.$modal.confirm('确认将订单' + row.sn + '修改为可开发票状态吗？').then(function () {
        invoicable(row.sn, 'NOT_INVOICED').then(res => {
          _this.$modal.msgSuccess("更新成功")
          _this.getList()
        })
      })
    },
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  top: 0;
  .el-dialog__body {
    padding: 0 30px;
  }
  .content {
    height: 50vh;
    overflow: hidden;
    overflow-y: scroll;
    .items {
      background: #f9f9f9;
      margin: 5px 0;
      padding: 5px;
    }
  }
}
</style>
